<template>
  <div class="app-container">

    <el-table v-loading="loading" :data="statisticsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" v-if="false"/>
      <el-table-column label="用户编号" align="center" prop="QualitygGroupId" />
      <el-table-column label="用户名" align="center" prop="QualitygGroupname" />
      <el-table-column label="质检次数" align="center" prop="num" />
      <el-table-column label="质检数据" align="center" prop="table" />
      <el-table-column label="质检规则描述" align="center" prop="description" />
      <el-table-column label="质检规则" align="center" prop="rule" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:statistics:edit']"
          >查看结果</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改【请填写功能名称】对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
        <div  class="app-container">
          <el-button @click="download">下载</el-button>
        </div>
        <div id="download"  class="parent">
          <div class="block"  >
            <div id="main" style="height:300px;width:350px" ></div>

          </div>
        </div>
    </el-dialog>
  </div>
</template>

<script>
import { listStatistics} from "@/api/business/statistics/statistics";
import * as echarts from 'echarts';
import html2canvas from "html2canvas"

export default {
  name: "Statistics",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      statisticsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        QualitygGroupId: null,
        ruleId: null,
        qualified: null,
        failed: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        QualitygGroupId: [
          { required: true, message: "$comment不能为空", trigger: "blur" }
        ],
        ruleId: [
          { required: true, message: "$comment不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 将echarts图表转换为canvas,并将canvas下载为图片
    download() {
      // 图表转换成canvas
      html2canvas(document.getElementById("download")).then(function (canvas) {
        var img = canvas
          .toDataURL("image/png")
          .replace("image/png", "image/octet-stream");
        // 创建a标签，实现下载
        var creatIMg = document.createElement("a");
        creatIMg.download = "图表.png"; // 设置下载的文件名，
        creatIMg.href = img; // 下载url
        document.body.appendChild(creatIMg);
        creatIMg.click();
        creatIMg.remove(); // 下载之后把创建的元素删除
      });
    },
    drawRose(row){
      var list;
      for (let i = 0; i < this.statisticsList.length; i++) {
        if (this.statisticsList[i].id === row.id){
          list = this.statisticsList[i];
        }
      }
      var data = [
        {
          name:"合格",
          value:list.qualified
        },
        {
          name:"不合格",
          value:list.failed
        },
      ];
      console.log(data);
      let element = document.getElementById('main');
      console.log(element);
        var myChart = echarts.init(element);

        // 填入数据
        myChart.setOption({
          title: {
            text: list.description,
            left: 'center'
          },
          tooltip: {
            trigger: 'item'
          },
          legend: {
            top: '10%',
            left: 'center'
          },
          series: [
            {
              // 根据名字对应到相应的系列
              type: 'pie',
              radius: ['40%', '60%'],
              avoidLabelOverlap: false,
              label: {
                show: true,
                position: "inside",
                formatter: `{d}%`,
              },
              emphasis: {
                label: {
                  show: true,
                  fontSize: '20',
                  fontWeight: 'bold'
                }
              },
              labelLine: {
                show: false
              },
              data: data
            }
          ]
        });
    },
    /** 查询【请填写功能名称】列表 */
    getList() {
      this.loading = true;
      listStatistics(this.queryParams).then(response => {
        this.statisticsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        QualitygGroupId: null,
        ruleId: null,
        qualified: null,
        failed: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加【请填写功能名称】";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.open = true;
      this.title = "质检结果";
      let that = this;
      var timer = setInterval(function () {
        // 判断页面所有资源已加载完毕
        if (document.readyState === "complete") {
          that.drawRose(row);
          window.clearInterval(timer);
        }
      }, 1000);
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateStatistics(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addStatistics(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除【请填写功能名称】编号为"' + ids + '"的数据项？').then(function() {
        return delStatistics(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/statistics/export', {
        ...this.queryParams
      }, `statistics_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style>
.block{
  width: 300px;
  height: 350px;
  margin: 15px;
  display: inline-block;
}

.parent{
  width: auto;
  height: auto;
  display: flex;
  flex-wrap: wrap;
}
</style>
